import cv2
import numpy as np
import matplotlib.pyplot as plt


# 绘制直方图函数
def grayHist(img):
    h, w = img.shape[:2]
    pixelSequence = img.reshape([h * w, ])
    numberBins = 256
    histogram, bins, patch = plt.hist(pixelSequence, numberBins,
                                      facecolor='black', histtype='bar')
    plt.xlabel("gray label")
    plt.ylabel("number of pixels")
    plt.axis([0, 255, 0, np.max(histogram)])
    plt.show()

img = cv2.imread("receipt_img/ticket2.jpg", 0)

# img = cv.imread("receipt_img/ticket2.jpg", 0)
# out = 0.75 * img
# # 进行数据截断，大于255的值截断为255
# out[out > 255] = 255
# # 数据类型转换
# out = np.around(out)
# out = out.astype(np.uint8)
# # 分别绘制处理前后的直方图
# # grayHist(img)
# grayHist(out)
# cv.imshow("img", img)
# cv.imshow("out", out)
# # cv.imwrite("ExpImg/origin.jpg", img)
# # cv.imwrite("ExpImg/out1.jpg", out)




# # 计算原图中出现的最小灰度级和最大灰度级
# # 使用函数计算
# Imin, Imax = cv2.minMaxLoc(img)[:2]
# # 使用numpy计算
# # Imax = np.max(img)
# # Imin = np.min(img)
# Omin, Omax = 0, 255
# # 计算a和b的值
# a = float(Omax - Omin) / (Imax - Imin)
# b = Omin - a * Imin
# out = a * img + b
# out = out.astype(np.uint8)
# grayHist(out)
# cv2.imshow("img", img)
# cv2.imshow("out2", out)
# #cv2.imwrite("ExpImg/out2.jpg", out)

# # 图像归一化
# fi = img / 255.0
# # 伽马变换
# gamma = 2
# out = np.power(fi, gamma)
# grayHist(out)
# cv2.imshow("img", img)
# cv2.imshow("out3", out)
# cv2.imwrite("ExpImg/out3.jpg", out)

# img = cv2.resize(img, None, fx=0.5, fy=0.5)
# 创建CLAHE对象
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
# 限制对比度的自适应阈值均衡化
dst = clahe.apply(img)
# 使用全局直方图均衡化
equa = cv2.equalizeHist(img)
# 分别显示原图，CLAHE，HE
cv2.imshow("img", img)
cv2.imshow("dst", dst)
grayHist(dst)
cv2.imwrite("ExpImg/out4.jpg", dst)

cv2.waitKey()